import {
    Message
} from 'antd';
/**
 * 通过event对象获取组件value，主要解决ie9兼容的问题
 * @param {Event} evt 
 */
const getValueFromEvent = evt => evt.target.value || evt.currentTarget.value || '';

const getValueFromQueryString = (url, key) => {
    if (!url || !key) {
        return null;
    }
    const reg = new RegExp('[\^?&]*' + key + '=([^&]*)[&$]*');
    const match = url.match(reg);
    return match && decodeURIComponent(match[1]);
};

const parseQuery = (urlStr) => {
    if (!urlStr || !(urlStr = urlStr.trim())) {
        return null;
    }
    let arr = urlStr.split('?');
    if (arr && arr[1]) {
        urlStr = arr[1];
    }
    arr = urlStr.split('&');
    let res = {};
    arr && arr.forEach(item => {
        const tmpArr = item.split('=');
        res[tmpArr[0]] = decodeURIComponent(tmpArr[1]);
    });
    return res;
};

const handelResult = (ret, callback, successMsg, errorMsg) => {
    if (ret.code === '0000') {
        Message.success(successMsg ? successMsg : ret.message || '操作成功');
    } else {
        Message.error(errorMsg ? errorMsg : ret.message || '操作失败');
    }
    if (callback && typeof callback === 'function') {
        callback(ret);
    }
}

//去除指定空参数
const buildParam = (param = {}, armArr = []) => {
    for (let key in param) {
        if (armArr.length === 0) {
            return param;
        } else if (armArr.indexOf(key) > -1) {
            if (param[key] === "") {
                delete(param[key])
            }
        }
    }
    return param;
}

export {
    getValueFromEvent,
    getValueFromQueryString,
    parseQuery,
    handelResult,
    buildParam
}